package com.donger.business.form.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.business.form.entity.SysFormData;
import com.donger.business.form.entity.SysFormDesign;
import com.donger.business.form.mapper.SysFormDataMapper;
import com.donger.business.form.mapper.SysFormDesignMapper;
import com.donger.business.form.service.SysFormDataService;
import com.donger.common.core.exception.BizException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 7326
 */
@Service
@AllArgsConstructor
public class SysFormDataServiceImpl extends ServiceImpl<SysFormDataMapper, SysFormData> implements SysFormDataService {
    private final SysFormDesignMapper sysFormDesignMapper;

    /**
     * 分页查询数据
     *
     * @param page
     * @return
     */
    @Override
    public IPage<JSONObject> pageList(Page<SysFormData> page, String formCode) {
        SysFormDesign sysFormDesign = sysFormDesignMapper.selectOne(Wrappers.<SysFormDesign>lambdaQuery().eq(SysFormDesign::getCode, formCode));
        if (sysFormDesign == null) {
            throw new BizException("表单编码错误");
        }
        Page<SysFormData> sysFormDataPage = this.baseMapper.selectPage(page, Wrappers.<SysFormData>lambdaQuery()
                .eq(SysFormData::getCode, formCode)
                .eq(SysFormData::getVersion, sysFormDesign.getVersion())
        );
        List<JSONObject> collect = sysFormDataPage.getRecords().stream()
                .map(item -> {
                    JSONObject jsonObject = JSONUtil.parseObj(item.getData());
                    jsonObject.put("id", item.getId());
                    return jsonObject;
                })
                .collect(Collectors.toList());

        Page<JSONObject> result = new Page<JSONObject>();
        result.setRecords(collect).setTotal(sysFormDataPage.getTotal()).setSize(sysFormDataPage.getSize()).setCurrent(sysFormDataPage.getCurrent());
        return result;
    }
}
